﻿using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace K9Nano.RemoteClient.LoadBalancing
{
    internal class BearerHttpMessageHandler : DelegatingHandler
    {
        private const string AuthorizationKey = "Authorization";

        private readonly IHttpContextAccessor _httpContextAccessor;

        public BearerHttpMessageHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            InnerHandler = new HttpClientHandler();
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!request.Headers.Contains(AuthorizationKey))
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext != null)
                {
                    if (httpContext.Request.Headers.ContainsKey(AuthorizationKey))
                    {
                        request.Headers.Add(AuthorizationKey, httpContext.Request.Headers[AuthorizationKey].First());
                    }
                }
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}